import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Upload, UploadFile, UploadProps } from "antd";
import { Box, SxProps } from "@mui/system";
import { AddOutline } from "antd-mobile-icons";
import PreviewWrapper from "./components/PreviewWrapper";
import FilePreview, { WxFilePreviewProps } from "./components/FilePreview";
import { UploadChangeParam } from "antd/es/upload";
import FileViewer from "./components/FileViewer";

export interface WxUploaderProps extends Omit<UploadProps, "onChange" | "fileList" | "listType">, Pick<WxFilePreviewProps, "filePreview"> {
  uploadIcon?: React.ReactNode;
  value?: UploadFile<any>[];
  sx?: SxProps;
  onChange?: (list: (UploadFile | string)[], info: UploadChangeParam<UploadFile<any>> | undefined) => void;
  beformOnChange?: (fileList: (UploadFile<any> | string)[], info: UploadChangeParam<UploadFile<any>> | undefined) => any[]; //onChange之前调用，作为表单组件时可用于格式化提交到表单的组件
}
const WxUploader = React.forwardRef(({ onChange, sx, beformOnChange, filePreview, value, children, uploadIcon, maxCount, ...otr }: WxUploaderProps, ref) => {
  const [fileList, setFileList] = useState<UploadFile<any>[]>([]);
  const [filesInfo, setFilesInfo] = useState<UploadChangeParam<UploadFile<any>>>();
  const UploadButton = useMemo(() => <button type={"button"}>{uploadIcon || <AddOutline />}</button>, [uploadIcon]);
  const [viewOpen, setViewOpen] = useState<number | undefined>(undefined);
  const onRemove = useCallback(
    (key: number) => {
      const newList = fileList.filter((file, index) => key !== index);
      const newInfo = filesInfo
        ? {
            ...filesInfo,
            file: filesInfo.fileList?.[key],
            fileList: filesInfo?.fileList?.filter((_file, index) => key !== index),
          }
        : filesInfo;
      setFileList(newList);
      setFilesInfo(newInfo);
      onChange && onChange(newList, newInfo);
    },
    [setFileList, setFilesInfo, fileList, filesInfo]
  );
  //当filesInfo变化时触发onChange并更新fileList
  //useEffect(() => {}, [filesInfo, setFileList, beformOnChange]);

  useEffect(() => {
    if (value !== undefined) {
      setFilesInfo({ fileList: value, file: value[0] });
      setFileList(value);
    }
  }, [value]);
  console.log(fileList);
  return (
    <Box sx={{ display: "flex", justifyContent: "flex-start", flexWrap: "wrap", ...sx }}>
      {fileList?.length
        ? fileList.map((file, index) => (
            <PreviewWrapper
              onViewFile={() => {
                setViewOpen(index);
              }}
              key={index}
              maskStatus={(file instanceof Object && file.status) || "done"}
              onRemove={() => onRemove(index)}
            >
              <FilePreview filePreview={filePreview} fileInfo={file}></FilePreview>
            </PreviewWrapper>
          ))
        : null}
      <Upload
        fileList={fileList}
        showUploadList={false}
        onChange={(info) => {
          setFilesInfo(info);
          setFileList(info?.fileList || []);
          onChange && onChange((beformOnChange && beformOnChange(info.fileList, filesInfo)) || info.fileList, filesInfo);
        }}
        maxCount={maxCount}
        {...otr}
      >
        <Box
          sx={{
            button: {
              border: 0,
              background: "none",
              backgroundColor: "#f5f5f5",
              width: 80,
              borderRadius: 1,
              fontSize: 32,
              height: 80,
              color: "#999999",
            },
          }}
        >
          {maxCount !== undefined && (filesInfo?.fileList?.length ?? 0) >= maxCount ? undefined : children == undefined ? UploadButton : children}
        </Box>
      </Upload>
      <FileViewer
        onClose={() => {
          setViewOpen(undefined);
        }}
        destroyOnClose
        defaultIndex={viewOpen}
        visible={viewOpen !== undefined}
        fileList={fileList}
      ></FileViewer>
    </Box>
  );
});

export default WxUploader;
